import path from 'path';

import { expect } from '@jest/globals';

import {
  addOhPackageDps,
  buildAppWithConfigAndCheck,
  commonJson5Operation,
  makeOneHap
} from '../../plugins/common-fun';
import {
  AbilityType,
  APIType,
  APIVersion,
  CaseLevel,
  LanguageType,
  ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';

const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,
    apiVersion: APIVersion.API10,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  },

  modulesOption: {
    [ModuleTemplateType.SharedLibrary]: 1,
  }
};

const testFun: TestCaseFun = async (project, taskConfig, record) => {
  // 1. 使entry模块依赖hsp模块
  const entryPath = project.getModule('entry').moduleRootPath();
  await addOhPackageDps(entryPath, {
    'shareLibrary': '../shareLibrary'
  });

  // 2. entry中新增target=test，选择test target进行构建 构建成功
  const entryBuildProfilePath = path.resolve(entryPath, 'build-profile.json5');
  await commonJson5Operation(entryBuildProfilePath, async (json5) => {
    json5.targets.push({ 'name': 'test' });
  });
  await makeOneHap('entry', 'default', 'test')(project, taskConfig, record);

  // 3. 工程新增product=test，并将test target apply到test product上，选择test target进行构建，构建失败
  const buildProfilePath = path.resolve(project.projectRootPath(), 'build-profile.json5');
  await commonJson5Operation(buildProfilePath, async (json5) => {
    const products = json5.app.products;
    products.push({
      'name': 'test',
      'signingConfig': 'default',
      'compileSdkVersion': products[0].compileSdkVersion,
      'compatibleSdkVersion': products[0].compatibleSdkVersion,
      'runtimeOS': products[0].runtimeOS,
    });

    const entryModuleConfig = (json5.modules as any[]).find((item) => item.name === 'entry');
    entryModuleConfig.targets.push({ 'name': 'test', 'applyToProducts': ['test'] });
  });
  try {
    await buildAppWithConfigAndCheck('test')(project, taskConfig, record);

    // 正常路径走不到这里，预判一个异常
    expect('测试场景执行异常抵达此处').toEqual('测试场景执行正常不抵达此处');
  } catch (e: any) {
    if (e.constructor.name === 'JestAssertionError') {
      throw e;
    }
    record.addStep('选择test target进行build-app构建', {
      stdout: e.stdout,
      stderr: e.stderr
    });
    expect(e.stderr).toContain('Unable to find target \'test\'');
  }

  // 4. hsp模块中新建target=test，并将test target apply到test product上，选择entry的test target进行构建， 构建成功
  const shareLibraryPath = project.getModule('shareLibrary').moduleRootPath();
  const shareLibraryBuildProfilePath = path.resolve(shareLibraryPath, 'build-profile.json5');
  await commonJson5Operation(shareLibraryBuildProfilePath, async (json5) => {
    json5.targets.push({ 'name': 'test' });
  });
  await commonJson5Operation(buildProfilePath, async (json5) => {
    const shareLibraryModuleConfig = (json5.modules as any[]).find((item) => item.name === 'shareLibrary');
    shareLibraryModuleConfig.targets.push({ 'name': 'test', 'applyToProducts': ['test'] });
  });
  await buildAppWithConfigAndCheck('test')(project, taskConfig, record);

  // 5. hsp模块删掉target test，并将default target apply到test product上，选择entry的test target进行构建， 构建成功
  await commonJson5Operation(shareLibraryBuildProfilePath, async (json5) => {
    json5.targets = [{ 'name': 'default' }];
  });
  await commonJson5Operation(buildProfilePath, async (json5) => {
    const shareLibraryModuleConfig = (json5.modules as any[]).find((item) => item.name === 'shareLibrary');
    shareLibraryModuleConfig.targets = [{ 'name': 'default', 'applyToProducts': ['test'] }];
  });
  await buildAppWithConfigAndCheck('test')(project, taskConfig, record);
};

// 将demo测试用例注册到测试用例中心
TestCaseBuilder.builder()
  .caseName('OPEN_LAB_AIDE_ZOS_HOS_STAGE_Shared_Library_api10_032')
  .description('32、entry引用hsp模块，entry添加targets编译')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.L1).build())
  .testFun(testFun)
  .load();
